const fs = require('fs'), path = require('path'), { globSync } = require('glob');
const root = __dirname, ref = new Set();

globSync(['**/*.js', '**/*.wxml', '**/*.wxss', '**/*.json'], { cwd: root })
  .forEach(f => fs.readFileSync(f, 'utf8')
    .match(/['"`][^'"`]*\.(png|jpg|jpeg|gif|svg|webp|ico)['"`]/gi)
    ?.forEach(m => {
      let f = m.slice(1, -1).replaceAll('/', '\\')
      ref.add(f.startsWith('\\') ? f.substring(1) : f)
    })
  );

globSync('static/images/**/*', { cwd: root, nodir: true })
  .forEach(f => {
    if (!ref.has(f)) {
      const p = path.resolve(root, f);
      fs.unlinkSync(p);
    }
  });